package com.music.detail.dao.impl;

import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.music.detail.dao.TrackDetailDao;
import com.music.domain.Commit;
import com.music.domain.Music;

@Repository
public class TrackDetailDaoImpl implements TrackDetailDao {
	
	@Autowired
	SessionFactory sessionFactory;
	
	@Override
	public Music findMusicById(String id) {
		Session session = sessionFactory.getCurrentSession();
		Music music = session.get(Music.class, id);
		return music;
	}

	@Override
	public List<Commit> findCommitsById(String id) {
		String hql="from Commit where musicid=:musicid";
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery(hql);
		query.setParameter("musicid", id);
		List<Commit> data = query.list();
		return data;
	}

	@Override
	public List<Music> findMusicByAuthorId(String authorId) {
		String hql="from Music where authorId=:authorId  order by createdate desc";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		query.setParameter("authorId", authorId);
		query.setFirstResult(0);
		query.setMaxResults(10);
		List<Music> data = query.list();
		return data;
	}

	@Override
	public List<Music> findMusicByCateId(String cateId) {
		String hql="from Music where cateId=:cateId order by createdate desc";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		query.setParameter("cateId", cateId);
		query.setFirstResult(0);
		query.setMaxResults(8);
		List<Music> data = query.list();
		return data;	
	}

	@Override
	public void addCommit(Map<String, Object> param) {
		String sql="INSERT INTO T_COMMIT(ID,TEXT,MUSICID,CREATENAME)"
				+ " VALUES(:ID,:TEXT,:MUSICID,:CREATENAME)";
		SQLQuery query = sessionFactory.getCurrentSession().createSQLQuery(sql);
		query.setParameter("ID", param.get("id"));
		query.setParameter("TEXT", param.get("text"));
		query.setParameter("MUSICID", param.get("musicid"));
		query.setParameter("CREATENAME", param.get("createname"));
		query.executeUpdate();
	}
}
